﻿using Microsoft.AspNetCore.Mvc.Filters;

namespace 日志的使用.自定义的内容
{
    /// <summary>
    /// 跳过Filter
    /// </summary>
    [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
    public class SkipFilterAttribute : Attribute
    {
    }


    /// <summary>
    /// 无需构造函数注入的方式：
    /// 局部的Filter, 需要继承Attribute，哪个Action需要就直接在该Action上添加该标签
    /// 当Action被调用时，先调用该Filter 
    /// 局部Filter, 不需要在Program中注册,在Action上使用 [SelfActionPartFilter]
    /// 
    /// 需要构造函数注入参数：
    /// 在Action上使用TypeFilter  [TypeFilter(typeof(SelfActionPartFilter))] 要求构造函数中的参数已经在IOC中
    /// 或在Action上使用ServiceFilter [ServiceFilter(typeof(SelfActionPartFilter))] 要求构造函数中的参数和该Filter已经在IOC中
    /// </summary>
    public class SelfActionPartFilter : Attribute, IAsyncActionFilter
    {
        private readonly ILogger<SelfActionPartFilter> logger;

        public SelfActionPartFilter(ILogger<SelfActionPartFilter> logger)
        {
            this.logger = logger;
        }

        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            await Console.Out.WriteLineAsync("SelfActionPartFilter执行了");
            if (context.ActionDescriptor.EndpointMetadata.Any(em => em.GetType() == typeof(SkipFilterAttribute))){
                logger.LogInfo($"这个Action或Controller上使用了[SkipFilter]标签");
            }
                logger.LogInfo($"OnActionExecutionAsync执行了");
            await next.Invoke();
        }
    }
}
